import { Inject, Injectable, CACHE_MANAGER } from '@nestjs/common'
import { Cache } from 'cache-manager'

const DEFAULT_EXPIRATION = 3600

@Injectable()
export class RedisService {
  constructor(@Inject(CACHE_MANAGER) private readonly cacheManager: Cache) {}

  public async set<T>(key: string, data: T, ttl = DEFAULT_EXPIRATION) {
    await this.cacheManager.set(key, data, { ttl })
  }

  public async get<T>(key: string) {
    return this.cacheManager.get<T>(key)
  }

  public async cache<T>(key: string, cb: () => Promise<T>): Promise<T> {
    const data = await this.get<T>(key)

    if (data) return data

    const freshData = await cb()
    this.set(key, freshData, DEFAULT_EXPIRATION)
    return freshData
  }
}
